package juc.ProducerAndConsumer;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * A执行完 调用B B执行完调用C C执行完调用A
 *
 * @author lwmzzz
 * @version 1.0
 * @date 2021/4/24 22:05
 * @description
 */
public class PAC3 {
    public static void main(String[] args) {
        Data3 data = new Data3();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data.printA();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data.printB();
            }

        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data.printC();
            }
        }, "C").start();

    }
}

class Data3 {
    private Lock lock = new ReentrantLock();

    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();

    private int a = 1;//1A 2B 3C

    public void printA() {
        lock.lock();
        try {
            while (a != 1) {
                condition1.await();
            }
            System.out.println(Thread.currentThread().getName() + "=>BBBB");
            a = 2;
            condition2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printB() {
        lock.lock();
        try {
            while (a != 2) {
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName() + "=>BBBB");
            a = 3;
            condition3.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printC() {
        lock.lock();
        try {
            while (a != 3) {
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName() + "=>CCCC");

            a = 1;
            condition1.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
